package com.xmy.cultivate.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.converter.CustomBigDecimalConverter;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.excelEntity.TranscriptScoreExcel;
import com.xmy.cultivate.entity.views.*;
import com.xmy.cultivate.mapper.TranscriptMapper;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;

import static com.xmy.cultivate.util.CommonUtil.validateNumber;

/**
 * <p>
 * 成绩管理 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2023-04-14
 */
@RestController
@RequestMapping("/api/transcript")
public class TranscriptController extends BaseController {

    @Autowired
    @Lazy
    ITranscriptService iTranscriptService;

    @Autowired
    @Lazy
    ITranscriptSetService iTranscriptSetService;

    @Autowired
    @Lazy
    IStudentService iStudentService;

    @Autowired
    @Lazy
    IdWorker idWorker;

    @Autowired
    @Lazy
    IDictService iDictService;

    @Autowired
    @Lazy
    IStudentAtSchoolScoreDivideService iStudentAtSchoolScoreDivideService;

    @Autowired
    @Lazy
    IStudentAtSchoolService iStudentAtSchoolService;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    TranscriptMapper transcriptMapper;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    IOrganizationService iOrganizationService;

    @Autowired
    @Lazy
    IStaffService iStaffService;

    @Autowired
    @Lazy
    IGradeService iGradeService;

    @Autowired
    @Lazy
    ISubjectsService iSubjectsService;

    @Autowired
    @Lazy
    IOrderDetailService iOrderDetailService;

    @Autowired
    IEnrollInfoService iEnrollInfoService;


    @Autowired
    IMidtermDateSetService iMidtermDateSetService;

    @Autowired
    IMqPushService iMqPushService;

    @Autowired
    ITranscriptSafetyDiffSetService iTranscriptSafetyDiffSetService;

    /**
     * 学员成绩
     *
     * @param pageNum
     * @param pageSize
     * @param schoolId
     * @param subjectsId
     * @param yearPart
     * @param quarterNum
     * @param examNum
     * @param yearClassId
     * @param gradeId
     * @param studentName
     * @return
     */
    @GetMapping()
    public Result findAll(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                          @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
                          @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
                          @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
                          @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
                          @RequestParam(value = "examNum", defaultValue = "") String examNum,
                          @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
                          @RequestParam(value = "gradeId", defaultValue = "") String gradeId,
                          @RequestParam(value = "studentName", defaultValue = "") String studentName,
                          @RequestParam(value = "isStatistics", defaultValue = "") String isStatistics,
                          @RequestParam(value = "startDate", defaultValue = "") String startDate,
                          @RequestParam(value = "endDate", defaultValue = "") String endDate) {
        try {
            IPage<Transcript> iPage = new Page<>(pageNum, pageSize);
            QueryWrapper<Transcript> transcriptQueryWrapper = new QueryWrapper<>();


            transcriptQueryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
            transcriptQueryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);

            String where = "deleted=0 ";
            if (StringUtils.isNotBlank(yearPart)) {
                where += "and year_part=" + yearPart + " ";
            }
            if (StringUtils.isNotBlank(quarterNum)) {
                where += "and quarter_num = " + quarterNum + " ";
            }


            if (StringUtils.isEmpty(schoolId)) {
                //transcriptQueryWrapper.in("school_id", this.baseSchoolIdList);
                transcriptQueryWrapper.inSql("student_id", "select student_id from order_apply where " + where + " and school_id in(" + this.baseSchoolIdStr + ")");
            } else {
                //transcriptQueryWrapper.eq("school_id", schoolId);
                transcriptQueryWrapper.inSql("student_id", "select student_id from order_apply where " + where + " and school_id in(" + schoolId + ")");

            }

            if (StringUtils.isNotBlank(subjectsId)) {
                transcriptQueryWrapper.inSql("subjects_id", subjectsId);
            } else {
                transcriptQueryWrapper.ne("subjects_id", 0);
            }

            transcriptQueryWrapper.eq(StringUtils.isNotBlank(examNum), "exam_num", examNum);
            transcriptQueryWrapper.inSql(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
            transcriptQueryWrapper.eq(StringUtils.isNotBlank(gradeId), "grade_id", gradeId);
            transcriptQueryWrapper.like(StringUtils.isNotBlank(studentName), "student_name", studentName);
            transcriptQueryWrapper.notIn("grade_section", 0);
            if (StringUtils.isNotBlank(isStatistics)) {
                if (isStatistics.equals("1")) {
                    transcriptQueryWrapper.eq("is_statistics", 1);
                } else {
                    transcriptQueryWrapper.eq("is_statistics", 0);
                }
            } else {
                transcriptQueryWrapper.ne("is_statistics", 0);
            }

            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
                String startDateStr = startDate + " " + "00:00:00";
                String endDateStr = endDate + " " + "23:59:59";
                transcriptQueryWrapper.between("created_at", startDateStr, endDateStr);
                transcriptQueryWrapper.orderByDesc("subjects_id", "year_class_id", "score_end");
            }

            iTranscriptService.page(iPage, transcriptQueryWrapper);
            for (Transcript transcript : iPage.getRecords()) {
                Student student = iStudentService.getById(transcript.getStudentId());
                if (student != null) {
                    transcript.setHeadImg(student.getHeadImg());
                }
                if (transcript.getSubjectsId() != null) {
                    String subjectsName = CommonUtil.getSubjectsNameForId(Integer.parseInt(transcript.getSubjectsId().toString()));
                    transcript.setSubjectsName(subjectsName);
                }
            }

            return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage());
        }
    }

    /**
     * 学员成绩
     *
     * @param pageNum
     * @param pageSize
     * @param schoolId
     * @param subjectsId
     * @param yearPart
     * @param quarterNum
     * @param examNum
     * @param yearClassId
     * @param gradeId
     * @param studentName
     * @return
     */
    @GetMapping("/findAllExport")
    public Result findAllExport(@RequestParam(value = "pageNum", defaultValue = "-1") Integer pageNum,
                                @RequestParam(value = "pageSize", defaultValue = "-1") Integer pageSize,
                                @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
                                @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
                                @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
                                @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
                                @RequestParam(value = "examNum", defaultValue = "") String examNum,
                                @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
                                @RequestParam(value = "gradeId", defaultValue = "") String gradeId,
                                @RequestParam(value = "studentName", defaultValue = "") String studentName,
                                @RequestParam(value = "isStatistics", defaultValue = "") String isStatistics,
                                @RequestParam(value = "startDate", defaultValue = "") String startDate,
                                @RequestParam(value = "endDate", defaultValue = "") String endDate) {
        try {
            IPage<Transcript> iPage = new Page<>(pageNum, pageSize);
            QueryWrapper<Transcript> transcriptQueryWrapper = new QueryWrapper<>();

            transcriptQueryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
            transcriptQueryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);

            if (StringUtils.isEmpty(schoolId)) {
                transcriptQueryWrapper.inSql("student_id", "select student_id from order_apply where year_part=" + yearPart + " and quarter_num = " + quarterNum + " and deleted=0 and school_id in(" + this.baseSchoolIdStr + ")");
            } else {
                transcriptQueryWrapper.inSql("student_id", "select student_id from order_apply where year_part=" + yearPart + " and quarter_num = " + quarterNum + " and deleted=0 and school_id in(" + schoolId + ")");
            }

            transcriptQueryWrapper.inSql(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
            transcriptQueryWrapper.eq(StringUtils.isNotBlank(examNum), "exam_num", examNum);
            transcriptQueryWrapper.inSql(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
            transcriptQueryWrapper.eq(StringUtils.isNotBlank(gradeId), "grade_id", gradeId);
            transcriptQueryWrapper.like(StringUtils.isNotBlank(studentName), "student_name", studentName);
            transcriptQueryWrapper.notIn("grade_section", 0, 3);
            if (StringUtils.isNotBlank(isStatistics)) {
                if (isStatistics.equals("1")) {
                    transcriptQueryWrapper.eq("is_statistics", 1);
                } else {
                    transcriptQueryWrapper.eq("is_statistics", 0);
                }
            } else {
                transcriptQueryWrapper.ne("is_statistics", 0);
            }

            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
                String startDateStr = startDate + " " + "00:00:00";
                String endDateStr = endDate + " " + "23:59:59";
                transcriptQueryWrapper.between("created_at", startDateStr, endDateStr);
                transcriptQueryWrapper.orderByDesc("subjects_id", "year_class_id", "score_end");
            }

            iTranscriptService.page(iPage, transcriptQueryWrapper);
            for (Transcript transcript : iPage.getRecords()) {
                Student student = iStudentService.getById(transcript.getStudentId());
                if (student != null) {
                    transcript.setHeadImg(student.getHeadImg());
                }
                if (transcript.getSubjectsId() != null) {
                    String subjectsName = CommonUtil.getSubjectsNameForId(Integer.parseInt(transcript.getSubjectsId().toString()));
                    transcript.setSubjectsName(subjectsName);
                }
            }

            ExcelExportHandle.export(response, "学员成绩", iPage.getRecords(), Transcript.class);
            return new Result(Code.OK, null, "导出成功");
        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage());
        }
    }


    @GetMapping("studentScoreExcel")
    public Result studentScoreExcel(
            @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "examNum", defaultValue = "") String examNum,
            @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
            @RequestParam(value = "gradeId", defaultValue = "") String gradeId,
            @RequestParam(value = "studentName", defaultValue = "") String studentName,
            @RequestParam(value = "isStatistics", defaultValue = "") String isStatistics) {
        try {
            QueryWrapper<Transcript> queryWrapper = new QueryWrapper<>();

            if (StringUtils.isEmpty(schoolId)) {
                queryWrapper.in("school_id", this.baseSchoolIdList);
            } else {
                queryWrapper.eq("school_id", schoolId);
            }
            queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
            queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
            queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
            queryWrapper.eq(StringUtils.isNotBlank(examNum), "exam_num", examNum);
            queryWrapper.eq(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
            queryWrapper.eq(StringUtils.isNotBlank(gradeId), "grade_id", gradeId);
            queryWrapper.like(StringUtils.isNotBlank(studentName), "student_name", studentName);
            queryWrapper.notIn("grade_section", 0, 3);
            if (StringUtils.isNotBlank(isStatistics)) {
                if (isStatistics.equals("1")) {
                    queryWrapper.eq("is_statistics", 1);
                } else {
                    queryWrapper.eq("is_statistics", 0);
                }
            } else {
                queryWrapper.ne("is_statistics", 0);
            }

            List<Transcript> list = iTranscriptService.list(queryWrapper);

            ExcelExportHandle.export(response, "学员成绩", list, Transcript.class);
            return new Result(Code.OK, null, "导出成功");
        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage(), "导出失败");
        }
    }


    /**
     * 获取录入成绩学生
     *
     * @return
     */
    @GetMapping("/getEnteringStudent")
    public Result getEnteringStudent(@RequestParam(value = "gradeIdList", defaultValue = "") String[] gradeIdList) {
        TranscriptSet transcriptSet = iTranscriptSetService.getById("1646797065822404608");
        Quarter quarter = iQuarterService.getQuarterForYearAndNum(transcriptSet.getTeacherYearPart(), transcriptSet.getTeacherQuarterNum());
        List<StudentTranscript> enteringStudentList = iTranscriptService.getEnteringStudent(gradeIdList, quarter, transcriptSet);
        return new Result(Code.OK, new PageResult(enteringStudentList, (long) enteringStudentList.size(), 1L));
    }

    @PostMapping()
    @Transactional
    public Result save(@RequestBody StudentTranscriptForGrade studentTranscriptForGrade) {
        TranscriptSet transcriptSet = iTranscriptSetService.getById("1646797065822404608");
        Quarter quarter = iQuarterService.getQuarterForYearAndNum(transcriptSet.getTeacherYearPart(), transcriptSet.getTeacherQuarterNum());

        StringBuilder stringBuilder = new StringBuilder();
        for (StudentTranscript studentTranscript : studentTranscriptForGrade.getStudentTranscriptList()) {
            for (StudentTranscriptItem studentTranscriptItem : studentTranscript.getStudentTranscriptItemList()) {
                for (SubjectsScore subjectsScore : studentTranscriptItem.getSubjectsScoreList()) {
                    subjectsScore.setReadingSchoolId(studentTranscriptItem.getReadingSchoolId());//报读学校
                    if (StringUtils.isNotBlank(subjectsScore.getScore()) && !validateNumber(subjectsScore.getScore())) {
                        StudentAtSchool studentAtSchool = iStudentAtSchoolService.getById(subjectsScore.getReadingSchoolId());
                        if (studentAtSchool == null) {
                            Student student = iStudentService.getById(studentTranscriptItem.getId());
                            stringBuilder.append(student.getName() + ":" + subjectsScore.getReadingSchoolId()).append("学校不存在").append(",");
                        } else {
                            QueryWrapper<StudentAtSchoolScoreDivide> studentAtSchoolScoreDivideQueryWrapper = new QueryWrapper<>();
                            studentAtSchoolScoreDivideQueryWrapper.eq("student_at_school_id", subjectsScore.getReadingSchoolId());
                            studentAtSchoolScoreDivideQueryWrapper.eq("grade_section", studentTranscriptItem.getGradeSection());
                            studentAtSchoolScoreDivideQueryWrapper.eq("score", subjectsScore.getScore().trim());
                            studentAtSchoolScoreDivideQueryWrapper.last("limit 1");
                            StudentAtSchoolScoreDivide studentAtSchoolScoreDivide = iStudentAtSchoolScoreDivideService.getOne(studentAtSchoolScoreDivideQueryWrapper);
                            if (studentAtSchoolScoreDivide == null) {
                                stringBuilder.append(studentTranscriptItem.getName()).append(subjectsScore.getScore()).append(",系统不存在学校：").append(studentAtSchool.getName()).append("分段").append(",");
                            }
                        }
                    }
                }
            }
        }

        if (stringBuilder.length() > 0) {
            return new Result(Code.ERROR, "", stringBuilder.toString() + "保存失败");
        }

        Integer i = 0;
        List<String> studentNameList = new ArrayList<>();
        for (StudentTranscript studentTranscript : studentTranscriptForGrade.getStudentTranscriptList()) {
            for (StudentTranscriptItem studentTranscriptItem : studentTranscript.getStudentTranscriptItemList()) {
                Student student = iStudentService.getById(studentTranscriptItem.getId());
                boolean isAdd = false;
                for (SubjectsScore subjectsScore : studentTranscriptItem.getSubjectsScoreList()) {
                    subjectsScore.setReadingSchoolId(studentTranscriptItem.getReadingSchoolId());//报读学校
                    if (StringUtils.isNotBlank(subjectsScore.getScore())) {//&& !validateNumber(subjectsScore.getScore())
                        Transcript transcript = iTranscriptService.getOneForQuarter(quarter.getYearPart(), quarter.getNum(), subjectsScore.getSubjectsId(), studentTranscriptItem.getId(), transcriptSet.getTeacherExamNum());
                        if (transcript == null) {
                            transcript = new Transcript();
                            transcript.setId(idWorker.nextId());
                        }
                        transcript.setScore(subjectsScore.getScore());
                        transcript.setRemark(subjectsScore.getRemark());

                        if (StringUtils.isEmpty(subjectsScore.getScore())) {
                            transcript.setScore("0");
                            transcript.setIsStatistics(0);
                            transcript.setScoreType(0);
                            continue;
                        } else {
                            if (subjectsScore.getScore() != null && subjectsScore.getScore().equals("0")) {
                                continue;
                            }
                            if (validateNumber(subjectsScore.getScore())) {
                                BigDecimal score = new BigDecimal(subjectsScore.getScore());
                                transcript.setScoreStart(score);
                                transcript.setScoreEnd(score);
                                transcript.setScoreType(1);//分数类型：1为数字，2为字母
                            } else {
                                //Transcript transcriptNew = iTranscriptService.getById(transcript.getId());
                                StudentAtSchool studentAtSchool = iStudentAtSchoolService.getById(subjectsScore.getReadingSchoolId());
                                QueryWrapper<StudentAtSchoolScoreDivide> studentAtSchoolScoreDivideQueryWrapper = new QueryWrapper<>();
                                studentAtSchoolScoreDivideQueryWrapper.eq("student_at_school_id", subjectsScore.getReadingSchoolId());
                                studentAtSchoolScoreDivideQueryWrapper.eq("grade_section", studentTranscriptItem.getGradeSection());
                                studentAtSchoolScoreDivideQueryWrapper.eq("score", subjectsScore.getScore().trim());
                                studentAtSchoolScoreDivideQueryWrapper.last("limit 1");
                                StudentAtSchoolScoreDivide studentAtSchoolScoreDivide = iStudentAtSchoolScoreDivideService.getOne(studentAtSchoolScoreDivideQueryWrapper);
                                transcript.setScoreStart(studentAtSchoolScoreDivide.getScoreStart());
                                transcript.setScoreEnd(studentAtSchoolScoreDivide.getScoreEnd());
                                transcript.setScoreType(2);//分数类型：1为数字，2为字母
                            }
                            transcript.setIsStatistics(1);
                            if (subjectsScore.getReadingSchoolId() != null && StringUtils.isNotBlank(String.valueOf(subjectsScore.getReadingSchoolId()))) {
                                if (student != null) {
                                    student.setReadingSchoolId(transcript.getReadingSchoolId());
                                    iStudentService.updateById(student);
                                }
                            }
                        }
                        StudentGrade studentGrade = iStudentGradeService.getStudentForLast(quarter.getYearPart(), quarter.getNum(), subjectsScore.getSubjectsId(), studentTranscriptItem.getId(), 1);
                        if (studentGrade != null) {
                            Organization organization = iOrganizationService.getById(studentGrade.getSchoolId());
                            transcript.setSchoolId(studentGrade.getSchoolId());
                            transcript.setSchoolName(organization.getName());
                            transcript.setYearClassId(studentGrade.getYearClassId());
                            transcript.setYearClassName(CommonUtil.getYearClassNameForId(studentGrade.getYearClassId()));
                            Grade grade = iGradeService.getById(studentGrade.getGradeId());
                            if (grade != null) {
                                transcript.setTeacherId(grade.getTeacherId());
                                transcript.setGradeId(grade.getId());
                                transcript.setGradeName(grade.getName());
                                Staff staff = iStaffService.getOneById(grade.getTeacherId());
                                if (staff != null) {
                                    transcript.setTeacherName(staff.getName());
                                }
                            }
                        } else {
                            transcript.setSchoolId(studentTranscriptItem.getSchoolId());
                            transcript.setYearClassId(studentTranscriptItem.getYearClassId());
                            transcript.setYearClassName(CommonUtil.getYearClassNameForId(studentTranscriptItem.getYearClassId()));
                            transcript.setGradeSection(studentTranscriptItem.getGradeSection());
                        }
                        transcript.setGradeSection(studentTranscriptItem.getGradeSection());
                        transcript.setYearPart(quarter.getYearPart());
                        transcript.setQuarterNum(quarter.getNum());
                        transcript.setQuarterName(quarter.getAliasName());
                        transcript.setStudentId(student.getId());
                        transcript.setStudentName(student.getName());
                        transcript.setExamNum(transcriptSet.getTeacherExamNum());//教师端录入考试名称
                        transcript.setExamName(transcriptSet.getTeacherExamName());
                        transcript.setReadingSchoolId(subjectsScore.getReadingSchoolId());
                        transcript.setSubjectsId(subjectsScore.getSubjectsId());
                        transcript.setSubjectsName(CommonUtil.getSubjectsNameForId(Integer.parseInt(subjectsScore.getSubjectsId().toString())));
                        boolean saveStatus = iTranscriptService.saveOrUpdate(transcript);
                        if (saveStatus) {
                            isAdd = true;
                        }
                    }
                }
                if (isAdd) {
                    i++;
                    studentNameList.add(student.getName());
                }
            }
        }

        return new Result(Code.OK, "", "成功添加了" + i + "个学生成绩，学生姓名为：" + String.join(",", studentNameList));
    }


    @GetMapping("/{id}")
    public Result findById(@PathVariable(value = "id") Long id) {
        Transcript transcript = iTranscriptService.getById(id);
        return new Result(Code.OK, transcript, "");
    }

    @PutMapping()
    public Result update(@RequestBody Transcript transcript) {
        if (transcript.getScore() == null) {
            transcript.setScore("0");
            transcript.setIsStatistics(0);
        } else {
            //数字
            if (validateNumber(transcript.getScore())) {
                BigDecimal score = new BigDecimal(transcript.getScore());
                transcript.setScoreStart(score);
                transcript.setScoreEnd(score);
                transcript.setScoreType(1);
            } else {

                if (transcript.getReadingSchoolId() == null) {
                    return new Result(Code.ERROR, "", "学校不能为空");
                }

                //字母
                QueryWrapper<StudentAtSchoolScoreDivide> studentAtSchoolScoreDivideQueryWrapper = new QueryWrapper<>();
                studentAtSchoolScoreDivideQueryWrapper.eq("student_at_school_id", transcript.getReadingSchoolId());
                studentAtSchoolScoreDivideQueryWrapper.eq("grade_section", transcript.getGradeSection());
                studentAtSchoolScoreDivideQueryWrapper.eq("score", transcript.getScore().trim());
                studentAtSchoolScoreDivideQueryWrapper.last("limit 1");
                StudentAtSchoolScoreDivide studentAtSchoolScoreDivide = iStudentAtSchoolScoreDivideService.getOne(studentAtSchoolScoreDivideQueryWrapper);
                if (studentAtSchoolScoreDivide == null) {
                    return new Result(Code.ERROR, "", "分段不存在，保存失败");
                }
                transcript.setScoreStart(studentAtSchoolScoreDivide.getScoreStart());
                transcript.setScoreEnd(studentAtSchoolScoreDivide.getScoreEnd());
                transcript.setScoreType(2);
            }
            transcript.setIsStatistics(1);
        }
        boolean rs = iTranscriptService.updateById(transcript);

        Transcript transcriptOne = iTranscriptService.getById(transcript.getId());

        /*Quarter quarterNow = iQuarterService.getNowQuarter();
        //获取上一个学期
        Quarter lastQuarter = iQuarterService.getLastQuarter(quarterNow.getYearPart(), quarterNow.getNum());
        if (lastQuarter.getType().equals(2)) {
            //如果上一学期为假期，再获取上一学期
            lastQuarter = iQuarterService.getLastQuarter(lastQuarter.getYearPart(), lastQuarter.getNum());
        }
        Transcript transcriptInfo = iTranscriptService.getById(transcript.getId());
        //根据分数更新可分班型，分层
        //iEnrollInfoService.addDataTranscript(quarterNow, lastQuarter, transcriptInfo.getStudentId(), transcriptInfo.getSubjectsId());
        */
        //分层
        try {
            ChaStudyPlan chaStudyPlan = new ChaStudyPlan();
            chaStudyPlan.setYearPart(transcriptOne.getYearPart());
            chaStudyPlan.setQuarterNum(transcriptOne.getQuarterNum());
            chaStudyPlan.setStudentId(transcriptOne.getStudentId());
            chaStudyPlan.setSubjectsId(transcriptOne.getSubjectsId());
            iMqPushService.chaStudyPlanAccuracy(chaStudyPlan);
        } catch (Exception e) {
        }

        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "成功" : "失败");
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Long id) {
        Transcript transcript = iTranscriptService.getById(id);
        if (transcript == null) {
            return new Result(Code.ERROR);
        }
        transcript.setIsStatistics(0);
        transcript.setScore("0");
        transcript.setScoreType(0);
        boolean rs = iTranscriptService.updateById(transcript);
        return new Result(rs ? Code.OK : Code.ERROR);
    }

    /**
     * 成绩数据
     *
     * @return
     */
    @GetMapping("/scoreData")
    public Result scoreData(
            @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "examNum", defaultValue = "") String examNum,
            @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
            @RequestParam(value = "include", defaultValue = "1") String include,
            @RequestParam(value = "type", defaultValue = "") String type,
            @RequestParam(value = "courseTypeId", defaultValue = "") String courseTypeId,
            @RequestParam(value = "gradeSection", defaultValue = "") String gradeSection,
            @RequestParam(value = "dataType", required = false, defaultValue = "1") String dataType
    ) {

        List<Long> schoolIdList = this.baseSchoolIdList;

        if (StringUtils.isEmpty(yearPart)) {
            return new Result(Code.ERROR, "", "年份不能为空");
        } else if (StringUtils.isEmpty(quarterNum)) {
            return new Result(Code.ERROR, "", "学期不能为空");
        } else if (StringUtils.isEmpty(examNum)) {
            return new Result(Code.ERROR, "", "考试名称不能为空");
        } else if (StringUtils.isEmpty(type)) {
            return new Result(Code.ERROR, "", "排行不能为空");
        }

        List<ScoreData> scoreDataList = iTranscriptService.scoreData(schoolId, schoolIdList, subjectsId, yearPart, quarterNum, examNum, gradeSection, yearClassId, type, include, courseTypeId, dataType);

        return new Result(Code.OK, new PageResult(scoreDataList, (long) scoreDataList.size(), 1L), "");
    }

    /**
     * 成绩数据Excel导出
     *
     * @return
     */
    @GetMapping("/scoreDataExcel")
    public Result scoreDataExcel(
            @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "examNum", defaultValue = "") String examNum,
            @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
            @RequestParam(value = "include", defaultValue = "1") String include,
            @RequestParam(value = "type", defaultValue = "") String type,
            @RequestParam(value = "courseTypeId", defaultValue = "") String courseTypeId,
            @RequestParam(value = "gradeSection", defaultValue = "") String gradeSection,
            @RequestParam(value = "dataType", required = false, defaultValue = "1") String dataType
    ) {

        List<Long> schoolIdList = this.baseSchoolIdList;

        if (StringUtils.isEmpty(yearPart)) {
            return new Result(Code.ERROR, "", "年份不能为空");
        } else if (StringUtils.isEmpty(quarterNum)) {
            return new Result(Code.ERROR, "", "学期不能为空");
        } else if (StringUtils.isEmpty(examNum)) {
            return new Result(Code.ERROR, "", "考试名称不能为空");
        } else if (StringUtils.isEmpty(type)) {
            return new Result(Code.ERROR, "", "排行不能为空");
        }

        List<ScoreDataExcel> scoreDataList = iTranscriptService.scoreDataExcel(schoolId, schoolIdList, subjectsId, yearPart, quarterNum, examNum, gradeSection, yearClassId, type, include, courseTypeId, dataType);

        ScoreDataExcel scoreDataAll = new ScoreDataExcel();
        scoreDataAll.setStudentAllCount(0);
        scoreDataAll.setStuRealityCount(0);
        scoreDataAll.setNotCounted(0);
        scoreDataAll.setNoPassCount(0);
        scoreDataAll.setPassCount(0);
        scoreDataAll.setCarryCount(0);

        for (ScoreDataExcel scoreData : scoreDataList) {
            scoreDataAll.setStudentAllCount(scoreDataAll.getStudentAllCount() + scoreData.getStudentAllCount());
            scoreDataAll.setStuRealityCount(scoreDataAll.getStuRealityCount() + scoreData.getStuRealityCount());
            scoreDataAll.setNotCounted(scoreDataAll.getNotCounted() + scoreData.getNotCounted());
            scoreDataAll.setNoPassCount(scoreDataAll.getNoPassCount() + scoreData.getNoPassCount());
            scoreDataAll.setPassCount(scoreDataAll.getPassCount() + scoreData.getPassCount());
            scoreDataAll.setCarryCount(scoreDataAll.getCarryCount() + scoreData.getCarryCount());
            if (Objects.nonNull(scoreDataAll.getRetrogressCount())) {
                scoreDataAll.setRetrogressCount(scoreDataAll.getRetrogressCount() + scoreData.getRetrogressCount());
            } else {
                scoreDataAll.setRetrogressCount(scoreData.getRetrogressCount());
            }
        }

        if (scoreDataAll.getStuRealityCount() > 0) {
            scoreDataAll.setNoPassRate(new BigDecimal(scoreDataAll.getNoPassCount()).divide(new BigDecimal(scoreDataAll.getStuRealityCount()), 4, BigDecimal.ROUND_HALF_UP));//不及格率
            scoreDataAll.setPassRate(new BigDecimal(scoreDataAll.getPassCount()).divide(new BigDecimal(scoreDataAll.getStuRealityCount()), 4, BigDecimal.ROUND_HALF_UP));//优秀率
            scoreDataAll.setCarryRate(new BigDecimal(scoreDataAll.getCarryCount()).divide(new BigDecimal(scoreDataAll.getStuRealityCount()), 4, BigDecimal.ROUND_HALF_UP));//优秀率
            scoreDataAll.setSecureRate(new BigDecimal(scoreDataAll.getPassCount()).divide(new BigDecimal(scoreDataAll.getStuRealityCount()), 4, BigDecimal.ROUND_HALF_UP).add(new BigDecimal(scoreDataAll.getCarryCount()).divide(new BigDecimal(scoreDataAll.getStuRealityCount()), 4, BigDecimal.ROUND_HALF_UP)));//安全值
        }

        scoreDataList.add(scoreDataAll);

        if (type.equals("1")) {
            scoreDataAll.setTeacherName("合计");
            ExcelUtil.export("成绩数据", scoreDataList, ScoreDataExcel.class, response);
        } else if (type.equals("2")) {
            scoreDataAll.setTeacherName("合计");
            ExcelUtil.export("成绩数据", scoreDataList, ScoreDataExcelTwo.class, response);
        } else if (type.equals("3")) {
            scoreDataAll.setTeacherName("合计");
            ExcelUtil.export("成绩数据", scoreDataList, ScoreDataExcelThree.class, response);
        } else if (type.equals("4")) {
            scoreDataAll.setSchoolName("合计");
            ExcelUtil.export("成绩数据", scoreDataList, ScoreDataExcelFour.class, response);
        }
        return new Result(Code.OK, null, "");
    }


    /**
     * 实际统计情况
     *
     * @return
     */
    @GetMapping("/scoreDataDetail")
    public Result scoreDataDetail(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "examNum", defaultValue = "") String examNum,
            @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
            @RequestParam(value = "type", defaultValue = "") String type,
            @RequestParam(value = "isStatistics", defaultValue = "") String isStatistics,
            @RequestParam(value = "gradeId", defaultValue = "") String gradeId,
            @RequestParam(value = "include", defaultValue = "1") String include,
            @RequestParam(value = "studentName", defaultValue = "") String studentName,
            @RequestParam(value = "courseTypeId", defaultValue = "") String courseTypeId,
            @RequestParam(value = "teacherId", defaultValue = "") String teacherId,
            @RequestParam(value = "gradeSection", defaultValue = "") String gradeSection,
            @RequestParam(value = "dataType", required = false, defaultValue = "1") String dataType
    ) {
        if (StringUtils.isEmpty(yearPart)) {
            return new Result(Code.ERROR, "", "年份不能为空");
        } else if (StringUtils.isEmpty(quarterNum)) {
            return new Result(Code.ERROR, "", "学期不能为空");
        } else if (StringUtils.isEmpty(examNum)) {
            return new Result(Code.ERROR, "", "考试名称不能为空");
        } else if (StringUtils.isEmpty(type)) {
            return new Result(Code.ERROR, "", "排行不能为空");
        }

        Quarter quarter = iQuarterService.getQuarterForYearAndNum(Integer.parseInt(yearPart), Integer.parseInt(quarterNum));
        String examName = CommonUtil.getExamNameForId(Integer.parseInt(examNum));
        Map<String, Object> map = new HashMap<>();
        map.put("examNum", examNum);
        map.put("examName", examName);
        map.put("yearPart", Integer.parseInt(yearPart));
        map.put("quarterNum", Integer.parseInt(quarterNum));
        map.put("quarterName", CommonUtil.getQuarterNameForId(Integer.parseInt(quarterNum)));

        QueryWrapper<TranscriptSafetyDiffSet> upWrapper = new QueryWrapper<>();
        upWrapper.le("quarter_id_start", quarter.getId());
        upWrapper.ge("quarter_id_end", quarter.getId());
        upWrapper.eq("exam_num", examNum);

        StringBuilder quarterNumConditions = new StringBuilder();
        if (StringUtils.isNotBlank(quarterNum)) {
            List<String> labelIdList = Arrays.asList(quarterNum.split(","));
            for (String strItem : labelIdList) {
                if (quarterNumConditions.length() > 0) {
                    quarterNumConditions.append(" OR ");
                }
                quarterNumConditions.append("FIND_IN_SET('").append(strItem).append("', quarter_num_str)");
            }
            if (quarterNumConditions.length() > 0) {
                upWrapper.apply(" (" + quarterNumConditions.toString() + ") ");
            }
        }

        StringBuilder yearClassIdConditions = new StringBuilder();
        if (StringUtils.isNotBlank(yearClassId)) {
            List<String> labelIdList = Arrays.asList(yearClassId.split(","));
            for (String strItem : labelIdList) {
                if (yearClassIdConditions.length() > 0) {
                    yearClassIdConditions.append(" OR ");
                }
                yearClassIdConditions.append("FIND_IN_SET('").append(strItem).append("', year_class_id_str)");
            }
            if (yearClassIdConditions.length() > 0) {
                upWrapper.apply(" (" + yearClassIdConditions.toString() + ") ");
            }
        }

        String subjectsId2 = subjectsId;
        if (StringUtils.isBlank(subjectsId)) {
            subjectsId2 = "1,2,3";//没有的话查所有
        }

        StringBuilder subjectsIdConditions = new StringBuilder();
        if (StringUtils.isNotBlank(subjectsId2)) {
            List<String> labelIdList = Arrays.asList(subjectsId2.split(","));
            for (String strItem : labelIdList) {
                if (subjectsIdConditions.length() > 0) {
                    subjectsIdConditions.append(" OR ");
                }
                subjectsIdConditions.append("FIND_IN_SET('").append(strItem).append("', subjects_id_str)");
            }
            if (subjectsIdConditions.length() > 0) {
                upWrapper.apply(" (" + subjectsIdConditions.toString() + ") ");
            }
        }


        List<TranscriptSafetyDiffSet> tTranscriptSafetyDiffSetList = iTranscriptSafetyDiffSetService.list(upWrapper);

        if (tTranscriptSafetyDiffSetList.size() == 1) {
            map.put("upType", 1);// 显示对比名字

            for (TranscriptSafetyDiffSet tTranscriptSafetyDiffSet : tTranscriptSafetyDiffSetList) {
                String upExamName = CommonUtil.getExamNameForId(tTranscriptSafetyDiffSet.getContrastExamNum());
                map.put("upExamName", upExamName);
                Quarter upQuarter = iQuarterService.getUpQuarter(Integer.parseInt(yearPart), Integer.parseInt(quarterNum), tTranscriptSafetyDiffSet.getContrastDiffNum());
                map.put("upExamNum", upQuarter.getSort());
                map.put("upYearPart", upQuarter.getYearPart());
                map.put("upQuarterName", CommonUtil.getQuarterNameForId(upQuarter.getNum()));
                map.put("upQuarterNum", upQuarter.getNum());
            }

        } else {
            map.put("upType", 0);// 显示对比分数
        }

//        Quarter upQuarter = CommonUtil.getUpQuarterForTerm(Integer.parseInt(yearPart), Integer.parseInt(quarterNum));
//        String upExamName = CommonUtil.getExamNameForId(upQuarter.getSort());
//        map.put("upExamNum", upQuarter.getSort());
//        map.put("upExamName", upExamName);
//        //Dict dict = iDictService.getQuarter(upQuarter.getNum());
//        map.put("upYearPart", upQuarter.getYearPart());
//        map.put("upQuarterName", upQuarter.getAliasName());
//        map.put("upQuarterNum", upQuarter.getNum());

        IPage<ScoreDataDetail> iPage = new Page<>(pageNum, pageSize);
        iTranscriptService.scoreDataDetail(iPage, schoolId, subjectsId, yearPart, quarterNum, examNum, gradeSection, yearClassId, type, teacherId, gradeId, isStatistics, include, studentName, courseTypeId, dataType);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages(), map), "");
    }

    /**
     * 成绩详情
     *
     * @return
     */
    @GetMapping("/otherScoreDataDetail")
    public Result otherScoreDataDetail(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "examNum", defaultValue = "") String examNum,
            @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
            @RequestParam(value = "type", defaultValue = "") String type,
            @RequestParam(value = "isStatistics", defaultValue = "") String isStatistics,
            @RequestParam(value = "gradeId", defaultValue = "") String gradeId,
            @RequestParam(value = "teacherId", defaultValue = "") String teacherId,
            @RequestParam(value = "gradeSection", defaultValue = "") String gradeSection,
            @RequestParam(value = "scoreDetailType", defaultValue = "") String scoreDetailType,
            @RequestParam(value = "include", defaultValue = "1") String include,
            @RequestParam(value = "studentName", defaultValue = "") String studentName,
            @RequestParam(value = "courseTypeId", defaultValue = "") String courseTypeId,
            @RequestParam(value = "status", defaultValue = "") String status,
            @RequestParam(value = "carryStatus", defaultValue = "") String carryStatus,
            @RequestParam(value = "dataType", required = false, defaultValue = "1") String dataType
    ) {
        if (StringUtils.isEmpty(yearPart)) {
            return new Result(Code.ERROR, "", "年份不能为空");
        } else if (StringUtils.isEmpty(quarterNum)) {
            return new Result(Code.ERROR, "", "学期不能为空");
        } else if (StringUtils.isEmpty("examNum")) {
            return new Result(Code.ERROR, "", "考试名称不能为空");
        } else if (StringUtils.isEmpty(type)) {
            return new Result(Code.ERROR, "", "排行不能为空");
        }

        Quarter quarter = iQuarterService.getQuarterForYearAndNum(Integer.parseInt(yearPart), Integer.parseInt(quarterNum));
        String examName = CommonUtil.getExamNameForId(Integer.parseInt(examNum));
        Map<String, Object> map = new HashMap<>();
        map.put("examNum", examNum);
        map.put("examName", examName);
        map.put("yearPart", Integer.parseInt(yearPart));
        map.put("quarterNum", Integer.parseInt(quarterNum));
        map.put("quarterName", CommonUtil.getQuarterNameForId(Integer.parseInt(quarterNum)));

        QueryWrapper<TranscriptSafetyDiffSet> upWrapper = new QueryWrapper<>();
        upWrapper.le("quarter_id_start", quarter.getId());
        upWrapper.ge("quarter_id_end", quarter.getId());
        upWrapper.eq("exam_num", examNum);

        StringBuilder quarterNumConditions = new StringBuilder();
        if (StringUtils.isNotBlank(quarterNum)) {
            List<String> labelIdList = Arrays.asList(quarterNum.split(","));
            for (String strItem : labelIdList) {
                if (quarterNumConditions.length() > 0) {
                    quarterNumConditions.append(" OR ");
                }
                quarterNumConditions.append("FIND_IN_SET('").append(strItem).append("', quarter_num_str)");
            }
            if (quarterNumConditions.length() > 0) {
                upWrapper.apply(" (" + quarterNumConditions.toString() + ") ");
            }
        }

        StringBuilder yearClassIdConditions = new StringBuilder();
        if (StringUtils.isNotBlank(yearClassId)) {
            List<String> labelIdList = Arrays.asList(yearClassId.split(","));
            for (String strItem : labelIdList) {
                if (yearClassIdConditions.length() > 0) {
                    yearClassIdConditions.append(" OR ");
                }
                yearClassIdConditions.append("FIND_IN_SET('").append(strItem).append("', year_class_id_str)");
            }
            if (yearClassIdConditions.length() > 0) {
                upWrapper.apply(" (" + yearClassIdConditions.toString() + ") ");
            }
        }

        String subjectsId2 = subjectsId;
        if (StringUtils.isBlank(subjectsId)) {
            subjectsId2 = "1,2,3";//没有的话查所有
        }

        StringBuilder subjectsIdConditions = new StringBuilder();
        if (StringUtils.isNotBlank(subjectsId2)) {
            List<String> labelIdList = Arrays.asList(subjectsId2.split(","));
            for (String strItem : labelIdList) {
                if (subjectsIdConditions.length() > 0) {
                    subjectsIdConditions.append(" OR ");
                }
                subjectsIdConditions.append("FIND_IN_SET('").append(strItem).append("', subjects_id_str)");
            }
            if (subjectsIdConditions.length() > 0) {
                upWrapper.apply(" (" + subjectsIdConditions.toString() + ") ");
            }
        }

        List<TranscriptSafetyDiffSet> tTranscriptSafetyDiffSetList = iTranscriptSafetyDiffSetService.list(upWrapper);

        if (tTranscriptSafetyDiffSetList.size() == 1) {
            map.put("upType", 1);// 显示对比名字

            for (TranscriptSafetyDiffSet tTranscriptSafetyDiffSet : tTranscriptSafetyDiffSetList) {
                String upExamName = CommonUtil.getExamNameForId(tTranscriptSafetyDiffSet.getContrastExamNum());
                map.put("upExamName", upExamName);
                Quarter upQuarter = iQuarterService.getUpQuarter(Integer.parseInt(yearPart), Integer.parseInt(quarterNum), tTranscriptSafetyDiffSet.getContrastDiffNum());
                map.put("upExamNum", upQuarter.getSort());
                map.put("upYearPart", upQuarter.getYearPart());
                map.put("upQuarterName", CommonUtil.getQuarterNameForId(upQuarter.getNum()));
                map.put("upQuarterNum", upQuarter.getNum());
            }

        } else {
            map.put("upType", 0);// 显示对比分数
        }

//        map.put("upExamNum", upQuarter.getSort());
//        map.put("upExamName", upExamName);
//        //Dict dict = iDictService.getQuarter(upQuarter.getNum());
//        map.put("upYearPart", upQuarter.getYearPart());
//        map.put("upQuarterName", upQuarter.getAliasName());
//        map.put("upQuarterNum", upQuarter.getNum());

        IPage<ScoreDataDetail> iPage = new Page<>(pageNum, pageSize);
        iTranscriptService.otherScoreDataDetail(iPage, schoolId, subjectsId, yearPart, quarterNum, examNum, gradeSection, yearClassId, type, teacherId, gradeId, scoreDetailType, status, include, studentName, courseTypeId, dataType, carryStatus);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages(), map), "");
    }


    @GetMapping("/getTranscriptList")
    public Result getTranscriptList(@RequestParam(value = "schoolId", defaultValue = "") Long schoolId,
                                    @RequestParam(value = "subjectsId", defaultValue = "") Integer subjectsId,
                                    @RequestParam(value = "yearPart", defaultValue = "") Integer yearPart,
                                    @RequestParam(value = "quarterNum", defaultValue = "") Integer quarterNum, Map<String, String> reMap,
                                    HttpServletResponse response) {
        String yearPartTranscript = reMap.get("yearPartTranscript");
        String quarterNumTranscript = reMap.get("quarterNumTranscript");
        String examNum = reMap.get("examNum");

//        Integer yearPartTranscript = 2023;
//        Integer quarterNumTranscript= 2;
//        Integer examNum = 3;

        List<TranscriptScoreExcel> transcriptScoreExcelList = iTranscriptService.getTranscriptList(schoolId, yearPart, quarterNum, Integer.valueOf(yearPartTranscript), Integer.valueOf(quarterNumTranscript), Integer.valueOf(examNum));

        ExcelExportHandleUtil.export(response, "", transcriptScoreExcelList, TranscriptScoreExcel.class);
        return new Result(Code.OK, null, "导出成功");
    }

    @PostMapping("/addScoreOne")
    public Result addScoreOne(@RequestBody Map<String, String> map) {
        Integer yearPart = Integer.parseInt(map.get("yearPart"));
        Integer quarterNum = Integer.parseInt(map.get("quarterNum"));
        Long studentId = Long.parseLong(map.get("studentId"));
        Long subjectsId = Long.parseLong(map.get("subjectsId"));
        Integer examNum = Integer.parseInt(map.get("examNum"));//考试名称id
        String score = map.get("score");
        String readingSchoolId = map.get("readingSchoolId");

        Quarter quarter = iQuarterService.getNowQuarter();

        if (score.trim().equals("0")) {
            return new Result(Code.ERROR, null, "分数不能为0");
        }

        Student student = iStudentService.getById(studentId);

        StudentGrade studentGrade = iStudentGradeService.getStudentForLast(quarter.getYearPart(), quarter.getNum(), subjectsId, studentId, 1);
        if (studentGrade == null) {
            return new Result(Code.ERROR, null, "不存在学生分班信息");
        }
        Integer gradeSection = CommonUtil.getGradeSection(studentGrade.getYearClassId());

        QueryWrapper<Transcript> transcriptQueryWrapper = new QueryWrapper<>();
        transcriptQueryWrapper.eq("year_part", yearPart);
        transcriptQueryWrapper.eq("quarter_num", quarterNum);
        transcriptQueryWrapper.eq("student_id", studentId);
        transcriptQueryWrapper.eq("subjects_id", subjectsId);
        transcriptQueryWrapper.eq("exam_num", examNum);
        transcriptQueryWrapper.last("limit 1");

        Transcript transcript = iTranscriptService.getOne(transcriptQueryWrapper);
        if (transcript == null) {
            transcript = new Transcript();
        } else {
            if (transcript.getIsStatistics().equals(1)) {
                return new Result(Code.ERROR, null, "已经添加过分数，添加失败");
            }
        }

        transcript.setSchoolId(studentGrade.getSchoolId());
        Organization organization = iOrganizationService.getById(studentGrade.getSchoolId());
        transcript.setSchoolName(organization.getName());
        if (StringUtils.isNotBlank(readingSchoolId)) {
            transcript.setReadingSchoolId(Long.parseLong(readingSchoolId));
        }
        Grade grade = iGradeService.getById(studentGrade.getGradeId());
        transcript.setTeacherId(grade.getTeacherId());
        Staff staff = iStaffService.getOneById(grade.getTeacherId());
        transcript.setTeacherName(staff.getName());
        transcript.setSubjectsId(subjectsId);
        transcript.setSubjectsName(CommonUtil.getSubjectsNameForId(Integer.parseInt(subjectsId.toString())));
        transcript.setYearPart(yearPart);
        transcript.setQuarterNum(quarterNum);
        transcript.setQuarterName(CommonUtil.getQuarterNameForId(quarterNum));
        transcript.setExamNum(examNum);
        transcript.setExamName(CommonUtil.getExamNameForId(examNum));
        transcript.setYearClassId(studentGrade.getYearClassId());
        transcript.setYearClassName(CommonUtil.getYearClassNameForId(studentGrade.getYearClassId()));
        transcript.setGradeSection(gradeSection);
        transcript.setGradeId(grade.getId());
        transcript.setGradeName(grade.getName());
        transcript.setScore(score);
        transcript.setStudentId(student.getId());
        transcript.setStudentName(student.getName());

        if (StringUtils.isEmpty(score)) {
            return new Result(Code.ERROR, null, "分数不能为空");
        } else {
            if (validateNumber(transcript.getScore())) {
                BigDecimal scoreB = new BigDecimal(transcript.getScore());
                transcript.setScoreStart(scoreB);
                transcript.setScoreEnd(scoreB);
                transcript.setScoreType(1);//分数类型：1为数字，2为字母
            } else {
                QueryWrapper<StudentAtSchoolScoreDivide> studentAtSchoolScoreDivideQueryWrapper = new QueryWrapper<>();
                studentAtSchoolScoreDivideQueryWrapper.eq("student_at_school_id", readingSchoolId);
                studentAtSchoolScoreDivideQueryWrapper.eq("grade_section", gradeSection);
                studentAtSchoolScoreDivideQueryWrapper.eq("score", transcript.getScore().trim());
                studentAtSchoolScoreDivideQueryWrapper.last("limit 1");
                StudentAtSchoolScoreDivide studentAtSchoolScoreDivide = iStudentAtSchoolScoreDivideService.getOne(studentAtSchoolScoreDivideQueryWrapper);
                if (studentAtSchoolScoreDivide == null) {
                    return new Result(Code.ERROR, null, "分数学校不存在");
                }
                transcript.setScoreStart(studentAtSchoolScoreDivide.getScoreStart());
                transcript.setScoreEnd(studentAtSchoolScoreDivide.getScoreEnd());
                transcript.setScoreType(2);//分数类型：1为数字，2为字母
            }
        }
        transcript.setIsStatistics(1);
        iTranscriptService.saveOrUpdate(transcript);
        try {
            ChaStudyPlan chaStudyPlan = new ChaStudyPlan();
            chaStudyPlan.setYearPart(transcript.getYearPart());
            chaStudyPlan.setQuarterNum(transcript.getQuarterNum());
            chaStudyPlan.setStudentId(transcript.getStudentId());
            chaStudyPlan.setSubjectsId(transcript.getSubjectsId());
            iMqPushService.chaStudyPlanAccuracy(chaStudyPlan);
        } catch (Exception e) {
        }


        return new Result(Code.OK, null, "添加成功");
    }


    @GetMapping("/getScoreSubjects")
    public Result getScoreSubjects(@RequestParam(value = "yearPart", required = false) Integer yearPart,
                                   @RequestParam(value = "quarterNum", required = false) Integer quarterNum,
                                   @RequestParam(value = "studentId", required = false) String studentId,
                                   @RequestParam(value = "yearClassId", required = true) Integer yearClassId,
                                   @RequestParam(value = "examNum", required = false, defaultValue = "3") Integer examNum
    ) {
        Quarter quarter = iQuarterService.getNowQuarter();
        Integer yearPartParam = yearPart;
        Integer quarterNumParam = quarterNum;
        if (yearPart == null) {
            yearPartParam = quarter.getYearPart();
            quarterNumParam = quarter.getNum();
        }

        Integer upNum = 2; //往前多少个学期
        if (quarterNum == 1 || quarterNum == 3) {
            upNum = 1;
        }

        //Quarter upQuarter = CommonUtil.getUpQuarterForTerm(yearPart, quarterNum);

        Quarter upQuarter = iQuarterService.getUpQuarter(yearPartParam, quarterNumParam, upNum);

        Integer isFinish = 1;
        List<Subjects> subjectsList = new ArrayList<>();

        if (quarterNumParam == 4 && examNum.equals(1)) {
            if ((yearClassId == 3 || yearClassId == 7 || yearClassId == 8)) {
                subjectsList = iSubjectsService.getTranscriptSubjects(yearPartParam, quarterNumParam, yearClassId, examNum);
            }
        } else {
            subjectsList = iSubjectsService.getTranscriptSubjects(yearPartParam, quarterNumParam, yearClassId, examNum);
        }

        List<SubjectsScore> subjectsScoreList = new ArrayList<>();
        for (Subjects subjects : subjectsList) {
            SubjectsScore subjectsScore = new SubjectsScore();
            subjectsScore.setSubjectsId(subjects.getId());
            subjectsScore.setSubjectsName(subjects.getName());
            subjectsScoreList.add(subjectsScore);
            if (StringUtils.isNotBlank(studentId)) {
                Transcript transcript = iTranscriptService.getOneForQuarter(quarter.getYearPart(), quarter.getNum(), subjects.getId(), Long.parseLong(studentId), upQuarter.getSort());
                if (transcript != null) {
                    subjectsScore.setScore(transcript.getScore());
                    subjectsScore.setReadingSchoolId(transcript.getReadingSchoolId());
                } else {
                    isFinish = 0;
                }
            }
        }
        String upExamName = CommonUtil.getExamNameForId(upQuarter.getSort());
        Map<String, Object> map = new HashMap<>();
        map.put("upExamName", upExamName);
        Dict dict = iDictService.getQuarter(upQuarter.getNum());
        if (dict != null) {
            map.put("upYearPart", upQuarter.getYearPart());
            map.put("upQuarterName", dict.getName());
        }
        map.put("upQuarterNum", upQuarter.getNum());
        map.put("isFinish", isFinish);
        return new Result(Code.OK, new PageResult(subjectsScoreList, (long) subjectsScoreList.size(), 1L, map), "");
    }

    /**
     * 获取上个学期需要填写的科目
     * 获取上个学期和本学期期中需要填写的科目成绩（2024-11-19）
     *
     * @param yearPart
     * @param quarterNum
     * @param studentId
     * @param yearClassId
     * @param examNum     1期中，3期末
     * @return
     */
    @GetMapping("/getUpScoreSubjects")
    public Result getUpScoreSubjects(@RequestParam(value = "yearPart", required = false) Integer yearPart,
                                     @RequestParam(value = "quarterNum", required = false) Integer quarterNum,
                                     @RequestParam(value = "studentId", required = false) String studentId,
                                     @RequestParam(value = "yearClassId", required = true) Integer yearClassId,
                                     @RequestParam(value = "examNum", required = false, defaultValue = "3") Integer examNum) {
        Quarter quarter = iQuarterService.getNowQuarter();
        Integer yearPartParam = yearPart;
        Integer quarterNumParam = quarterNum;
        if (yearPart == null) {
            yearPartParam = quarter.getYearPart();
            quarterNumParam = quarter.getNum();
        }

        Integer upNum = 2; //往前多少个学期
        if (examNum.equals(3)) {
            if (quarterNum == 1 || quarterNum == 3) {
                upNum = 1;
            }
        } else {
            if (quarterNum == 1 || quarterNum == 3) {
                upNum = 1;
            } else {
                upNum = 0;
            }
        }

        Quarter upQuarter = iQuarterService.getUpQuarter(yearPartParam, quarterNumParam, upNum);

        //七年级秋季班录入的成绩为市模拟成绩
        if (yearClassId.equals(7) && quarterNumParam.equals(4)) {
            if (examNum.equals(3)) {
                examNum = 5;
            }
        }

        Integer isFinish = 1;
        List<Subjects> subjectsList = new ArrayList<>();
        LocalDate dateNow = LocalDate.now();
        if (examNum.equals(1)) {
            if (quarterNumParam == 2 || quarterNumParam == 4) {

                // 获取期中考试日期
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("year_part", yearPartParam);
                queryWrapper.eq("quarter_num", quarterNumParam);
                Integer gradeSection = CommonUtil.getGradeSection(yearClassId);
                queryWrapper.eq("grade_section", gradeSection);
                queryWrapper.last("limit 1");
                MidtermDateSet midtermDate = iMidtermDateSetService.getOne(queryWrapper);

                // 判断当前是否大于期中考试日期
                if (midtermDate != null && (dateNow.isAfter(midtermDate.getMidtermDate()) || dateNow.isEqual(midtermDate.getMidtermDate()))) {
                    subjectsList = iSubjectsService.getTranscriptSubjects(yearPartParam, quarterNumParam, yearClassId, examNum);
                }

                /*if (quarter.getMidtermDate()!=null && (dateNow.isAfter(quarter.getMidtermDate()) || dateNow.isEqual(quarter.getMidtermDate()))){
                    if ((yearClassId == 3 || yearClassId == 7 || yearClassId == 8)){
                        subjectsList = iSubjectsService.getTranscriptSubjects(yearPartParam, quarterNumParam, yearClassId,examNum);
                    }
                }*/
            }
        } else {
            subjectsList = iSubjectsService.getTranscriptSubjects(yearPartParam, quarterNumParam, yearClassId, examNum);
        }

        if (quarterNum.equals(4) && examNum.equals(3)) {
            yearClassId = yearClassId - 1;
            if (yearClassId < 0) {
                yearClassId = 0;
            }
        }
        List<SubjectsScore> subjectsScoreList = new ArrayList<>();
        for (Subjects subjects : subjectsList) {
            SubjectsScore subjectsScore = new SubjectsScore();
            subjectsScore.setSubjectsId(subjects.getId());
            subjectsScore.setSubjectsName(subjects.getName());
            subjectsScoreList.add(subjectsScore);
            if (StringUtils.isNotBlank(studentId)) {
                Transcript transcript = iTranscriptService.getOneForQuarter(upQuarter.getYearPart(), upQuarter.getNum(), subjects.getId(), Long.parseLong(studentId), examNum);
                if (transcript != null) {
                    subjectsScore.setScore(transcript.getScore());
                    subjectsScore.setReadingSchoolId(transcript.getReadingSchoolId());
                } else {
                    isFinish = 0;
                }
            }
        }
        //String upExamName = CommonUtil.getExamNameForId(examNum);
        Map<String, Object> map = new HashMap<>();
        // 上学期考试名称
        String upExamName = CommonUtil.getExamNameForId(examNum);
        map.put("upExamName", upExamName);
        Dict dict = iDictService.getQuarter(upQuarter.getNum());
        if (dict != null) {
            map.put("upYearPart", upQuarter.getYearPart());
            map.put("upQuarterName", dict.getName());
        }
        map.put("upQuarterNum", upQuarter.getNum());
        map.put("isFinish", isFinish);
        return new Result(Code.OK, new PageResult(subjectsScoreList, (long) subjectsScoreList.size(), 1L, map), "");
    }


    @PostMapping("/addScoreForStudentId")
    public Result addScoreForStudentId(@RequestBody Transcript transcript) {
        Long studentId = transcript.getStudentId();
        Integer yearPart = transcript.getYearPart();
        Integer quarterNum = transcript.getQuarterNum();
        Long subjectsId = transcript.getSubjectsId();
        Integer examNum = transcript.getExamNum();
        String score = transcript.getScore();
        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("subjects_id", subjectsId);
        orderDetailQueryWrapper.eq("lesson_type", 1);
        orderDetailQueryWrapper.eq("student_id", studentId);
        orderDetailQueryWrapper.ne("status", 2);
        orderDetailQueryWrapper.orderByDesc("id");
        orderDetailQueryWrapper.last("limit 1");
        QueryWrapper<OrderDetail> orderDetailQueryWrapper2 = orderDetailQueryWrapper.clone();

        orderDetailQueryWrapper.eq("year_part", yearPart);
        orderDetailQueryWrapper.eq("quarter_num", quarterNum);


        OrderDetail orderDetail = iOrderDetailService.getOne(orderDetailQueryWrapper);
        if (orderDetail == null) {
            Quarter quarterNow = iQuarterService.getNowQuarter();
            orderDetailQueryWrapper2.eq("year_part", quarterNow.getYearPart());
            orderDetailQueryWrapper2.eq("quarter_num", quarterNow.getNum());
            orderDetail = iOrderDetailService.getOne(orderDetailQueryWrapper2);
        }

        Transcript transcriptInfo = new Transcript();
        if (orderDetail != null) {
            transcriptInfo.setSchoolId(orderDetail.getSchoolId());
            Organization organization = iOrganizationService.getById(orderDetail.getSchoolId());
            transcriptInfo.setSchoolName(organization.getName());
            Student student = iStudentService.getById(orderDetail.getStudentId());

            transcriptInfo.setStudentId(orderDetail.getStudentId());
            transcriptInfo.setStudentName(student.getName());
            transcriptInfo.setSubjectsId(orderDetail.getSubjectsId());
            transcriptInfo.setSubjectsName(CommonUtil.getSubjectsNameForId(Integer.parseInt(orderDetail.getSubjectsId().toString())));
            transcriptInfo.setYearPart(yearPart);
            transcriptInfo.setQuarterNum(quarterNum);
            transcriptInfo.setQuarterName(CommonUtil.getQuarterNameForId(quarterNum));
            transcriptInfo.setExamNum(examNum);
            transcriptInfo.setExamName(CommonUtil.getExamNameForId(examNum));
            transcriptInfo.setYearClassId(orderDetail.getYearClassId());
            transcriptInfo.setYearClassName(CommonUtil.getYearClassNameForId(orderDetail.getYearClassId()));
            transcriptInfo.setGradeSection(CommonUtil.getGradeSection(orderDetail.getYearClassId()));
            transcriptInfo.setScore(score);
            transcriptInfo.setScoreStart(new BigDecimal(score));
            transcriptInfo.setScoreEnd(new BigDecimal(score));
            transcriptInfo.setScoreType(1);
            transcriptInfo.setIsStatistics(1);
            iTranscriptService.save(transcriptInfo);

            try {
                ChaStudyPlan chaStudyPlan = new ChaStudyPlan();
                chaStudyPlan.setYearPart(transcriptInfo.getYearPart());
                chaStudyPlan.setQuarterNum(transcriptInfo.getQuarterNum());
                chaStudyPlan.setStudentId(transcriptInfo.getStudentId());
                chaStudyPlan.setSubjectsId(transcriptInfo.getSubjectsId());
                iMqPushService.chaStudyPlanAccuracy(chaStudyPlan);
            } catch (Exception e) {
            }

        } else {
            return new Result(Code.ERROR, "", "订单不存在，不能添加");
        }
        return new Result(Code.OK, "", "添加成功");
    }


    @GetMapping("/getNewStudentScore")
    public Result getNewStudentScore(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                     @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                                     @RequestParam(value = "schoolId", required = false) String schoolId,
                                     @RequestParam(value = "subjectsId", required = false) String subjectsId,
                                     @RequestParam(value = "yearClassId", required = false) String yearClassId,
                                     @RequestParam(value = "startDate") String startDate,
                                     @RequestParam(value = "endDate") String endDate,
                                     @RequestParam(value = "studentName", required = false) String studentName,
                                     @RequestParam(value = "isExport", required = false, defaultValue = "0") String isExport) {

        IPage<ResNewStuScore> page = new Page<>(pageNum, pageSize);

        Quarter quarter = iQuarterService.getNowQuarter();

        //获取上一个学期
        Quarter lastQuarter = iQuarterService.getLastQuarter(quarter.getYearPart(), quarter.getNum());
        if (lastQuarter.getType().equals(2)) {
            //如果上一学期为假期，再获取上一学期
            lastQuarter = iQuarterService.getLastQuarter(lastQuarter.getYearPart(), lastQuarter.getNum());
        }

        String scoreYearPart = lastQuarter.getYearPart().toString();
        String scoreQuarterNum = lastQuarter.getNum().toString();
        String schoolIds = schoolId;
        if (StringUtils.isBlank(schoolId)) {
            schoolIds = this.baseSchoolIdStr;
        }

        iTranscriptService.newStudentScore(page, schoolIds, subjectsId, yearClassId, startDate, endDate, scoreYearPart, scoreQuarterNum, studentName);
        if (isExport.equals("1")) {
            page = new Page<>(pageNum, page.getTotal());
            iTranscriptService.newStudentScore(page, schoolId, subjectsId, yearClassId, startDate, endDate, scoreYearPart, scoreQuarterNum, studentName);
            ExcelExportHandle.export(response, "新学员成绩", page.getRecords(), ResNewStuScore.class);
            return new Result(Code.OK, null, "导出成功");
        } else {
            return new Result(Code.OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()));
        }
    }

}
